package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "套餐接口")
@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishService dishService;

    /**
     * 添加套餐信息
     * @param setmealDto
     * @return
     */
    @ApiOperation("添加套餐信息")
    @CacheEvict(cacheNames = "setmealCache", allEntries = true)
    @PostMapping
    public R save(@RequestBody SetmealDto setmealDto) {
        log.info("setmealDto = {}", setmealDto);

        setmealService.saveWithDishing(setmealDto);

        return R.success();
    }


    /**
     * 分页查询
     * @return
     */
    @ApiOperation("分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码",dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "pageSize", value = "页面大小",dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "name", value = "套餐名称", dataTypeClass = String.class)
    })
    @GetMapping("/page")
    public R<Page<SetmealDto>> pageSetmeal(@RequestParam(required = false,defaultValue = "1") Integer page,
                                           @RequestParam(required = false,defaultValue = "10") Integer pageSize,String name) {
        log.info("page = {}, pageSize = {}, name = {}", page, pageSize, name);

        Page<SetmealDto> pageInfo = setmealService.page(page, pageSize, name);

        return R.success(pageInfo);
    }


    /**
     * 删除套餐信息
     * @param ids
     * @return
     */
    @ApiOperation("删除套餐信息")
    @DeleteMapping
    public R delete(@RequestParam List<Long> ids) {
        log.info("需要删除的id: {}", ids);

        setmealService.deleteWithDishing(ids);

        return R.success();
    }


    /**
     * 根据条件查询套餐信息
     *
     * 做数据的缓存
     *
     * @param setmeal
     * @return
     */
    @ApiOperation("根据条件查询套餐信息")
    @Cacheable(cacheNames = "setmealCache", key = "'setmeal_'+ #a0.categoryId + '_' + #a0.status")
    @GetMapping("/list")
    public R<List<Setmeal>> list(Setmeal setmeal) {
        log.info("套餐数据查询: setmeal = {}", setmeal);

        // 条件分装
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(setmeal.getCategoryId() != null,Setmeal::getCategoryId, setmeal.getCategoryId());
        lambdaQueryWrapper.eq(setmeal.getStatus() != null,Setmeal::getStatus, setmeal.getStatus());
        lambdaQueryWrapper.orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> setmealList = setmealService.list(lambdaQueryWrapper);

        return R.success(setmealList);
    }


    /**
     * 修改数据时的数据回显
     * @return
     */
    @ApiOperation("修改数据时的数据回显")
    @GetMapping("/{id}")
    public R<SetmealDto> getById(@PathVariable Long id) {
        log.info("修改数据的id = {}", id);

        SetmealDto setmealDto = new SetmealDto();

        // 1. 根据id查询套餐的基本信息
        Setmeal setmeal = setmealService.getById(id);
        if (setmeal == null) {
            return R.error("为查询到数据！");
        }
        BeanUtils.copyProperties(setmeal,setmealDto);

        // 2. 查询菜品分类信息
        Category category = categoryService.getById(setmeal.getCategoryId());
        if (category != null) {
            setmealDto.setCategoryName(category.getName());
        }

        // 3. 查询套餐的菜品信息
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SetmealDish::getSetmealId,id);
        List<SetmealDish> setmealDishList = setmealDishService.list(lambdaQueryWrapper);

        setmealDto.setSetmealDishes(setmealDishList);


        return R.success(setmealDto);
    }


    /**
     * 修改套餐信息
     * @return
     */
    @ApiOperation("修改套餐信息")
    @CacheEvict(cacheNames = "setmealCache", allEntries = true)
    @PutMapping
    public R update(@RequestBody SetmealDto setmealDto) {

        log.info("修改的数据 setmealDto = {}", setmealDto);

        setmealService.updateWithDishing(setmealDto);

        return R.success();
    }


    /**
     * 修改套餐的状态
     * 如果起售套餐，套餐中包含的有停售的商品时，不能起售
     * @param status
     * @param ids
     * @return
     */
    @ApiOperation("修改套餐的状态")
    @CacheEvict(cacheNames = "setmealCache", allEntries = true)
    @PostMapping("/status/{status}")
    public R updateByStatus(@PathVariable Integer status,@RequestParam List<Long> ids) {
        log.info("修改的状态 status = {status}, 需要修改的id值 ids = {}", ids);

        // 判断当前操作是否时起售套餐
        if(status == 1) {
            // 获取套餐中所有的菜品信息
            LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
            setmealDishLambdaQueryWrapper.in(SetmealDish::getSetmealId, ids);

            List<SetmealDish> setmealDishList = setmealDishService.list(setmealDishLambdaQueryWrapper);

            // 获取所有的菜品id
            List<Long> list = setmealDishList.stream().map(SetmealDish::getDishId).collect(Collectors.toList());

            // 查询套餐中是否有停售的菜品
            LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishLambdaQueryWrapper.in(Dish::getId, list);
            dishLambdaQueryWrapper.eq(Dish::getStatus, 0);
            int count = dishService.count(dishLambdaQueryWrapper);

            if (count > 0) {
                throw new CustomException("套餐中有停售的菜品信息，不能直接起售！");
            }
        }

        // 修改套餐的状态
        LambdaUpdateWrapper<Setmeal> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.in(Setmeal::getId, ids);
        lambdaUpdateWrapper.set(Setmeal::getStatus, status);

        setmealService.update(new Setmeal(),lambdaUpdateWrapper);

        return R.success();
    }

}
